angular.module('nonghua.controllers.system', [])
    .controller('AccountUpgradeFarmerCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        $scope.accountInfo = {};
        var resourceName = "account_upgrade_step2";
        $scope.userRoleStatus={};
        $scope.accountInfo.gender="男";
        $scope.userRoleStatus.roleUpdated = false  ;
        $scope.info = {};
        //if(_user_has_role("升级成农户",$rootScope.user) && $rootScope.user.upgrade_status == "升级成农户" ){
        //    $scope.userRoleStatus.roleUpdated = true;
        //    $scope.info.updateMsg="您已提交用户升级申请，请耐心等待！"
        //}
        if(!empty($rootScope.user.farmer) ){
            $scope.accountInfo = $rootScope.user.farmer;
        }
        if(_user_has_role("升级成农户",$rootScope.user) && $rootScope.user.upgrade_status == "拒绝成农户" ){
            $scope.info.updateMsg="您被拒绝成为农户！"

        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.accountInfo) && !empty($scope.accountInfo.addr_id) ? $scope.accountInfo.addr_id : "",
            farmer:'',
            level:5
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                role: "升级成农户",
                farmer_id: !empty($scope.accountInfo.farmer_id) ? $scope.accountInfo.farmer_id : "",
                farmer_name: $scope.accountInfo.farmer_name,
                village:$scope.addressOption.village,
                town:$scope.addressOption.town,
                county:$scope.addressOption.county,
                city:$scope.addressOption.city,
                province:$scope.addressOption.province,
                gender: $scope.accountInfo.gender,
                cell: $scope.accountInfo.cell,
                details: $scope.accountInfo.addr_details,
                type: $scope.accountInfo.type,
                farm_area: $scope.accountInfo.farm_area,
                soil_type: $scope.accountInfo.soil_type,
                soil_fertility: $scope.accountInfo.soil_fertility,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.success == 1) {
                        $scope.info.updateMsg="您已提交用户升级申请，请耐心等待！"
                        $scope.userRoleStatus.roleUpdated = true;
                        $scope.$apply();
                    } else {
                        alert("操作失败！"+data.form_errors);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('MainCtrl', function ($scope,$rootScope,$ionicSlideBoxDelegate) {
        //首页
        $scope.isEmployee = _user_is_employee($rootScope.user);
        $scope.$on('get_permission',function(e,d){
            $rootScope.access = {
                invoice:$rootScope.user_access('view own invoice'),
                stock_info:$rootScope.user_access('view own stock_info'),
                monthly_report:$rootScope.user_access('view own monthly_report'),
                sales_log:$rootScope.user_access('view own sales_log'),

                capacity:$rootScope.user_access('view own capacity'),
                competitors:$rootScope.user_access('view own competitors'),
                brand_sales:$rootScope.user_access('view own brand_sales'),
                plant_structure:$rootScope.user_access('view own plant_structure'),

                farmer:$rootScope.user_access('view own farmer'),
                plant_info:$rootScope.user_access('view own plant_info'),
                soil_info:$rootScope.user_access('view own soil_info'),
                fertilizer_case:$rootScope.user_access('view own fertilizer_case'),
                revisit:$rootScope.user_access('view own revisit'),

                village_activity:$rootScope.user_access('view own village_activity'),
                experts_work:$rootScope.user_access('view own experts_work'),
                retailstore:$rootScope.user_access('view own retailstore'),
                genuine_code:$rootScope.user_access('genuine verification'),

                upgrade: $rootScope.canUpgrade($rootScope.user.roles)
            };
            $scope.$apply();
        });
        $scope.reloadPage = function() {
            $rootScope.articlePromoted = {};
            var path_to_article_promoted = 'app-promoted';
            views_datasource_get_view_result(path_to_article_promoted, {
                success: function (data) {
                    var length = data.nodes.length;
                    if (length != 0) {
                        console.log(data);
                        for (var i = 0; i < length; i++) {
                            var nid = data.nodes[i].node.nid;
                            $rootScope['articlePromoted'][nid] = {
                                nid: nid,
                                title: data.nodes[i].node.title,
                                body: data.nodes[i].node.body,
                                time: data.nodes[i].node.time,
                                typeId: data.nodes[i].node.typeId,
                                typeName: data.nodes[i].node.typeName
                            };
                            if (data.nodes[i].node.img) {
                                $rootScope['articlePromoted'][nid].img = data.nodes[i].node.img.src;
                            } else {
                                //to-do: add default article pic
                            }
                        }

                    }
                    $rootScope.$apply();
                    $ionicSlideBoxDelegate.update();
                }
            });
            $scope.$broadcast('scroll.refreshComplete');
        };
        $scope.reloadPage();
    })

    .controller('ChangePictureCtrl', function ($scope, $jrCrop, cordovaCamera, $rootScope, $state, $ionicLoading) {
        $scope.cameraimage = $rootScope.user.picture;
        $scope.selectPicture = function() {
            // Image picker will load images according to these settings
            var options = {
                maximumImagesCount: 1,
                width: 800,
                //height: 800,
                quality: 100
            };
            $scope.cameraimage = "";
            $scope.imagefile = "";
            window.imagePicker.getPictures(
                function (results) {
                    if (results.length == 1) {
                        //$scope.cameraimage = results[0];
                        $jrCrop.crop({
                            url: results[0],
                            width: 400,
                            height: 400,
                            cancelText: '取消',
                            chooseText: '选择'
                        }).then(function(canvas) {
                            // success!
                            $scope.cameraimage = canvas.toDataURL("image/jpeg",1);
                            $scope.imagefile = $scope.cameraimage.replace("data:image/jpeg;base64,", ""); ;
                            $scope.$apply();
                        }, function() {
                            // User canceled or couldn't load image.
                            //alert("User canceled or couldn't load image.");
                        });
                    } else {
                        //cancelled selection
                    }
                }, function (error) {
                    console.log('Error: ' + error);
                }, options
            );
        };

        $scope.takePicture = function () {
            var options = {
                quality: 100,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                allowEdit: true,
                encodingType: Camera.EncodingType.JPEG,
                targetWidth: 400,
                targetHeight: 400
            };
            $scope.cameraimage = "";
            $scope.imagefile = "";
            // udpate camera image directive
            cordovaCamera.getPicture(options).then(function (imageData) {
                $scope.cameraimage = "data:image/jpeg;base64," + imageData;
                $scope.imagefile = imageData;
                $scope.$apply();
            }, function (err) {
                console.log('Failed because: ');
                console.log(err);
            });
        };

        $scope.submitPicture = function () {
            if (empty($scope.imagefile)) {
                alert("请选择或者拍摄一张头像！");
            } else {
                $ionicLoading.show({
                    content: '请稍后',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                var file = {
                    "file": $scope.imagefile,
                    "filename": "user_picture_" + $rootScope.user.uid+ ".jpg",
                    "filepath": "public://user_picture_" + $rootScope.user.uid+ ".jpg"
                };
                file_create(file, {
                    success: function(result) {
                        //alert(JSON.stringify(result));
                        var account = {
                            'uid': $rootScope.user.uid,
                            picture: result.fid
                        };
                        user_save(account, {
                            error: function (xhr, status, message) {
                                alert("头像修改失败！");
                                $ionicLoading.hide();
                            },
                            success: function (user_save_result) {
                                //alert('头像修改成功');
                                $rootScope.user.picture = $scope.cameraimage;
                                $ionicLoading.hide();
                                //$rootScope.user.picture = "http://www.metercomm.com.cn/nonghua/sites/default/files/user_picture_" + $rootScope.user.uid+ ".jpg";
                                $state.go('tabs.my-account');
                            }
                        });
                    },
                    error: function(xhr, status, message) {
                        alert("头像上传失败！");
                        $ionicLoading.hide();
                    }
                });
            }
        }
    })

    .controller('ErrorCtrl', function ($scope, $state, $rootScope, $ionicLoading, $ionicNavBarDelegate, $timeout) {
        $ionicNavBarDelegate.showBackButton(false);
        $scope.reload = function () {
            $ionicLoading.show({
                content: '重新连接',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            userInit($rootScope, $ionicLoading, $state, $timeout);
        };
    })

    .controller('IntroCtrl', function ($scope, $state, $ionicSlideBoxDelegate) {
        // 欢迎页，启动服务
        $scope.startApp = function () {
            $state.go('tabs.main');
        };
        $scope.next = function () {
            $ionicSlideBoxDelegate.next();
        };
        $scope.previous = function () {
            $ionicSlideBoxDelegate.previous();
        };

        // Called each time the slide changes
        $scope.slideChanged = function (index) {
            $scope.slideIndex = index;
        };
    })

    .controller('MyAccountCtrl', function ($scope, $ionicLoading, $rootScope, $state,UserInfo) {

        if($rootScope.user.uid != 0){
            UserInfo.refreshUserInfo($rootScope.user.uid).then(function(user){
                $scope.user = user;
                if(_user_has_role("升级成农户", $scope.user)||_user_is_only_authenticated($scope.user)){
                    $scope.user.canUpgrade = true;
                }else{
                    $scope.user.canUpgrade = false;
                }
            })
        }

        $scope.user = $rootScope.user;
        $scope.exit = function() {
            ionic.Platform.exitApp();
        };

        $scope.logout = function(){
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            user_logout({
                success: function (result) {
                    $ionicLoading.hide();
                    $scope.$apply(function(){
                        $rootScope.user = {};
                        $rootScope.user.uid = 0;
                        $rootScope.user.roles = {"1":"anonymous user"};
                        $rootScope.user.permissions = [];
                        $scope.user = $rootScope.user;
                    });
                    _get_user_permissions({
                        success:function(result) {
                            $rootScope.user.permissions = result;
                            $scope.user.permissions = result;
                            $rootScope.$broadcast('get_permission', '');
                            $scope.$apply();
                        }
                    });
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        };

        $scope.login = function () {
            $scope.message = "";
            if(empty($scope.user.username) || empty($scope.user.password)){
                $scope.message="用户名或密码为空！";
                return;
            }
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            user_login($scope.user.username, $scope.user.password, {
                success: function (result) {
                    $ionicLoading.hide();
                    $rootScope.user = {};
                    $rootScope.user.uid = result.user.uid;
                    $rootScope.user.name = result.user.name;
                    if(!empty(result.user.field_cell)){
                        $rootScope.user.cell = result.user.field_cell.und[0].value;
                    }
                    if(!empty(result.user.farmer_name)){
                        $rootScope.user.farmer_name= result.user.farmer_name;
                    }
                    if(!empty(result.user.field_upgrade_status)){
                        $rootScope.user.upgrade_status= result.user.field_upgrade_status.und[0].value;
                    }
                    $rootScope.user.roles = result.user.roles;
                    if(!empty(result.user.picture) && !empty(result.user.picture.url)){
                        $rootScope.user.picture = result.user.picture.url;
                    }else{
                        $rootScope.user.picture=$rootScope.picture_default;
                    }
                    $scope.user = $rootScope.user ;
                    if(_user_has_role("升级成农户", $scope.user)||_user_is_only_authenticated($scope.user)){
                        $scope.user.canUpgrade = true;
                    }else{
                        $scope.user.canUpgrade = false;
                    }
                    _get_user_permissions({
                        success:function(result) {
                            $rootScope.user.permissions = result;
                            $scope.user.permissions = result;
                            $rootScope.$broadcast('get_permission', '');
                            $scope.$apply();
                        }
                    });
                    $scope.user = $rootScope.user;
                    $scope.message = "";
                    $scope.$apply();
                    $state.go('tabs.my-account');
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    //alert(message);
                    $scope.message = "用户名/密码不正确";
                }
            });
        };
        $scope.upgrade = function(){
            var path_to_source = 'mobile_service_resources/account_upgrade_step1';

            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                resource: "account_upgrade_step1",
                param: {},
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.success == 1) {
                        $rootScope.user.roles=data.roles;
                        $rootScope.user.upgrade_status=data.status;
                        $rootScope.user.farmer=data.farmer;
                        if(!empty( $rootScope.user.farmer)){
                            $rootScope.user.farmer.farmer_name = str_trim( $rootScope.user.farmer.farmer_name);
                        }
                        $state.go('account-upgrade-farmer');
                    } else {
                        alert("操作失败！");
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })

    .controller('ModifyPassCtrl', function ($scope,  $stateParams,$ionicSideMenuDelegate, $ionicLoading, $rootScope,$timeout,$state,Role,Sms) {
        $scope.data = {};
        $scope.password={};
        if(Role.isRole('administrator')){
            $scope.data.userCellDisabled = false;
        }else{
            $scope.data.userCellDisabled = true;
            $scope.data.userCell = $rootScope.user.cell;
        }
        $scope.getCheckResult = function () {
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            Sms.getCheckResult(
                {
                    checkDigit:$scope.data.checkDigit
                }
            ).then(function(result){
                    $ionicLoading.hide();
                    if(result.checkDigitBack){
                        $state.go('modify-password.modifyPass');
                    }else{
                        alert(result.error);
                    }
                });
        };
        $scope.submitForm = function(data){
            var account = {
                uid:$rootScope.user.uid,
                pass:$scope.password.password1
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });

            user_save(account, {
                error: function (xhr, status, message) {
                    // If there were any form errors, display them in an alert.
                    $ionicLoading.hide();
                    $state.go('error-page');
                },
                success: function (result) {
                    $ionicLoading.hide();
                    //todo
                    alert('修改成功');
                    $state.go('tabs.my-account');
                }
            });

        }
    })

    .controller('ForgotPassCtrl', function ($scope,  $stateParams,$ionicSideMenuDelegate, $ionicLoading, $rootScope,$timeout,$state,Role,Sms) {
        $scope.data = {};
        $scope.password = {};
        $scope.getCheckResult = function () {
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            Sms.checkAndLogin(
                {
                    checkDigit:$scope.data.checkDigit,
                    userCell:$scope.data.userCell
                }
            ).then(function(result){
                    if(result.checkDigitBack){
                       $rootScope.user = result.user;
                        Drupal.csrf_token = false;
                        services_get_csrf_token({
                            reset:true,
                            success: function(token) {
                                Drupal.csrf_token = true;
                            },
                            error: function(xhr, status, message) {
                                $state.go("error");
                            }
                        });
                        system_connect({
                            success : function () {
                                $ionicLoading.hide();
                                $state.go('forgot-password.modifyPass')
                            }
                        });
                    }else{
                        $ionicLoading.hide();
                        alert(result.error);
                    }
                });
        }
        $scope.submitForm = function(){
            var account = {
                pass: $scope.password.password1,
                uid:$rootScope.user.uid
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });

            user_save(account, {
                error: function (xhr, status, message) {
                    // If there were any form errors, display them in an alert.
                    $ionicLoading.hide();
                    $state.go('error');
                },
                success: function (result) {
                    $ionicLoading.hide();
                    //todo
                    alert('修改成功');
                    $state.go('tabs.my-account');
                }
            });
        }
    })

    .controller('RegisterCtrl', function ($scope, $ionicLoading, $rootScope, $state,$timeout,Sms) {
        $scope.user={};
        $scope.password = {};

        $scope.register = function(data){
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            Sms.getCheckResultRegister(
                {
                    checkDigit:$scope.user.checkDigit,
                    field_cell: $scope.user.userCell,
                    name:$scope.user.userName,
                }
            ).then(function(result){
                   
                    if(result.checkDigitBack){
                        $scope.register_continue();
                    }else{
                        $ionicLoading.hide();
                        alert(result.error);
                        $ionicLoading.hide();
                    }
                });
            $scope.register_continue = function(){
                var account = {
                    name:$scope.user.userName,
                    pass:$scope.password.password1,
                    field_cell: {
                        und: [
                            { value:  $scope.user.userCell }
                        ]
                    }
                    //field_username: {
                    //    und: [
                    //        { value:  $scope.user.userName }
                    //    ]
                    //}
                };

                user_register(account,{
                    error: function(xhr, status, message) {
                        // If there were any form errors, display them in an alert.
                        $ionicLoading.hide();
                        if (status == 406) {
                            alert('手机号已占用！');
                        } else {
                            $state.go('error');
                        }
                    },
                    success: function () {
                        $ionicLoading.hide();
                        //todo
                        alert('注册成功,请登录');
                        $state.go('tabs.my-account');
                    }
                });
            }
        }
    })

    .controller('PersonalInfoCtrl', function ($scope,  $stateParams,$ionicSideMenuDelegate, $ionicLoading, $rootScope,$timeout,$state,Role,Sms) {
        $scope.data = {};
        $scope.submitForm = function(data){
            var account = {
                uid:$rootScope.user.uid,
                signature:$scope.data.userName,
            };
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });

            user_save(account, {
                error: function (xhr, status, message) {
                    // If there were any form errors, display them in an alert.
                    $ionicLoading.hide();
                    $state.go('error-page');
                },
                success: function (result) {
                    $ionicLoading.hide();
                    //todo
                    alert('修改成功');
                    $state.go('tabs.my-account');
                }
            });

        }
    });


